from django.shortcuts import render,redirect,HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from django.http import JsonResponse
from app01 import models
from app01.utils.form import TaskModelForm
from app01.utils.pagination import Pagination


def task_add(request):
    form=TaskModelForm()
    return render(request, 'task_add.html', {'form':form})


@csrf_exempt
def task_add_ajax(request):
    print(request.POST)
    #校验
    form=TaskModelForm(request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))
    data_dict = {"status": False,"error":form.errors}
    return HttpResponse(json.dumps(data_dict))

def task_list(request):
    if request.method == 'GET':
        # 传查询条件显示列表
        # 创建空字典
        data_dict = {}
        # 前端传过来的参数
        search_data = request.GET.get('q', '')
        if search_data:
            # 把前端传过来的参数放到字典里
            data_dict['mobile__contains'] = search_data
        queryset = models.Task.objects.filter(**data_dict).order_by("-level")
        page_object = Pagination(request, queryset)
        form = TaskModelForm()
        context = {'form': form,
                   'search_data': search_data,
                   'page_queryset': page_object.page_queryset,  # 分完页的数据
                   'page_string': page_object.html()}  # 页码
        return render(request, 'task_list.html', context)


def task_delete(request,nid):
        models.Task.objects.filter(id=nid).delete()
        return redirect('/task/list/')

def task_edit(request):
    uid = request.GET.get("id")
    row_object = models.Task.objects.filter(id=uid).values('title', 'level', 'detial', ).first()
    if not row_object:
        return JsonResponse({"status": False, "error": "不存在该数据"})
    result = {'status': True,
              'data': row_object
              }
    return JsonResponse(result)